package com.rpc.proxy;

import com.rpc.common.Invocation;
import com.rpc.config.RpcServiceConfig;
import com.rpc.handler.RpcClientHandler;
import io.netty.handler.timeout.TimeoutException;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * 调用服务端接口
 */
public class ProxyFactory {

    public static <T> T getProxy(Class interfaceClass, RpcClientHandler handler, String server, RpcServiceConfig rpcServiceConfig){
        Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Invocation invocation = new Invocation(interfaceClass.getName(),method.getName(),rpcServiceConfig.getGroup(),rpcServiceConfig.getVersion(),method.getParameterTypes(),args);
                CompletableFuture completableFuture = handler.sendRpcService(server,invocation);
                Object o = null;
                try{
                    o = completableFuture.get(5,TimeUnit.SECONDS);
                }catch(TimeoutException timeoutException){
                    timeoutException.printStackTrace();
                }
                return o;
            }
        });
        return (T)proxyInstance;
    }
}
